package com.example.telephoneBook;



import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.sql.SqlHelp;

public class LoginActivity extends Activity {
	private EditText user;
	private EditText password;
	private Button login;
	private SqlHelp dbhelp;
	private SQLiteDatabase db;
	
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		SharedPreferences sp = getSharedPreferences("config", MODE_PRIVATE);
		if(sp.getString("startKey", "").equals("1")){
			startActivity(new Intent(this,MainListActivity.class));	
			finish();
		}
		user = (EditText)findViewById(R.id.account_edittext);
		password = (EditText)findViewById(R.id.password_edittext);
		login = (Button)findViewById(R.id.login_button);
		inituser();
		login.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO 自动生成的方法存根
				dbhelp = new SqlHelp(LoginActivity.this, SqlHelp.DBName);
				db = dbhelp.getReadableDatabase();
				Cursor cursor = db.query(SqlHelp.TableUser, null,
						"username=? and password=?", new String[] {
								user.getText().toString().trim(),
								password.getText().toString().trim() },
						null, null, null);
				int a = cursor.getCount();
				db.close();
				cursor.close();
				if (a != 0) {
					Toast.makeText(LoginActivity.this, "登陆成功!",
							Toast.LENGTH_LONG).show();
					SharedPreferences sp = getSharedPreferences("config", MODE_PRIVATE);
							Editor editor = sp.edit();
							editor.putString("startKey", "1");
							editor.commit();
						
					startActivity(new Intent(LoginActivity.this,
							MainListActivity.class));
				} else {
					Toast.makeText(LoginActivity.this, "登陆失败!",
							Toast.LENGTH_LONG).show();
				}

			}
		});
		
		
	}
	public void inituser(){
		dbhelp = new SqlHelp(LoginActivity.this, SqlHelp.DBName);
		db = dbhelp.getReadableDatabase();
		Cursor cursor = db.query(SqlHelp.TableUser, null, "username=?",
				new String[] { "admin" }, null, null, null);
		int a = cursor.getCount();
		if(a == 0){
			ContentValues values = new ContentValues();
			values.put("username", "admin");
			values.put("password", "admin");
			db.insert(SqlHelp.TableUser, null, values);
			Toast.makeText(LoginActivity.this, "测试账号初始化成功!",
					Toast.LENGTH_LONG).show();
		}
		db.close();
		cursor.close();
	}
	
	public  void register2(View view){
		startActivity(new Intent(LoginActivity.this,
				RegisterActivity.class));
	}
		
}
